<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\26 0026
 * Time: 13:56
 */

namespace app\Lib\Model\Tag;


use app\Lib\Exception\BlException;
use app\Lib\Model\DbModel\StyleTag;
use app\Lib\Model\Tag\TagBase;

abstract class EditTag extends  TagBase implements \app\Lib\InterfaceIn\Tag\EditTag
{
    /** @var StyleTag $table */
    public  $table;
    public  $tagId;

    private function getData(){
        $data   = $this->handleData();
        $model  = $this->table;
        $data[$model->_update_time] = time();
        $data[$model->_update_id] = $this->opUser->getUid();
        $data[$model->_id]          = $this->tagId;
        return $data;
    }

    /**
     * 参数验证
     * @param $data
     * @return bool
     * @throws BlException
     */
    private function check($data){
        $table  = $this->table;
        if(empty($data[$table->_tag_name])){
            throw new BlException('标签名称不能为空');
        }
        if(empty($data[$table->_update_id])){
            throw new BlException('创建人获取失败');
        }
        if(empty($data[$table->_update_time])){
            throw new BlException('创建时间获取失败');
        }
        if(empty($data[$table->_id])){
            throw new BlException('未获取到修改项');
        }
        $id     = $table->where($table->_id,$data[$table->_id])->value($table->_id);
        if(!$id){
            throw new BlException('未查询到修改项');
        }
        $result = $table->where(
            [$table->_tag_name=>$data[$table->_tag_name],$table->_id=>['neq',$data[$table->_id]]]
        )->value($table->_id);
        if($result){
            throw new BlException('标签名称已存在');
        }

        return true;
    }

    /**
     * 代码执行
     * @return bool
     * @throws BlException
     */
    public function run()
    {
        $data   = $this->getData();
        $model  = $this->table;
        $this->check($data);
        $result = $model->update($data);
        if(!$result){
            throw new BlException('修改失败');
        }
        return true;
    }
}